'use strict';
import React from 'react';
import {
    View,
    Text,
    Image,
    TextInput,
    TouchableOpacity,
    DatePickerAndroid,
    Platform,
    StyleSheet,
    Keyboard,
    ScrollView,
    ActivityIndicator,
    DatePickerIOS,
    Modal,
} from 'react-native';
import ToolBar from '../Components/ToolBar';
import ImagePicker from 'react-native-image-picker';
import Toast from '../Utils/toast';
import Global from '../Commom/GlobalConst';

const width = Global.Const.size.width;
const height = Global.Const.size.height;
import FoundAPIService from '../Commom/FoundAPIService';
import DateUtil from '../Commom/DateUtil';
const styles = StyleSheet.create({
    flexRow: {
        height: 45,
        padding: 15,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: 'white',
        marginBottom: 1,
        paddingTop: 0,
        paddingBottom: 0,
    },
    contentText: {
        fontSize: 14,
        flex: 1,
        textAlign: 'right',
    },
    choiceImagesBox: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        alignItems: 'center',
        padding: 15,
        backgroundColor: 'white',
        marginBottom: 10
    },
    datePickerBox: {
        padding: 15,
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 10,
        marginBottom: 10,
        backgroundColor: 'white'
    },
    image: {
        width: (width - 50) / 4,
        height: (width - 50) / 4,
        marginRight: 5,
        marginTop: 5,
    },

    modalStyle: {  
    flex:1,
    alignItems: 'stretch',
    flexDirection: 'column',
    justifyContent:'flex-end',  
    backgroundColor:'rgba(200,200,200,0.3)', 
 
 },  
    DatePickerCancelView:{  
    height: height-214,    
    // backgroundColor:'rgba(25,172,26,0.3)',  
    },  
    DatePickerView:{  
        height: 214,
        backgroundColor:'#fff',         
    }, 
});

/**
 * 发起自驾同游
 */
class InitiatedWithTour extends React.Component {
  
    constructor(props) {
        super(props);
        let date = new Date();
        date = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
        this.state = {
            departureDate: date,
            returnDate: date,
            choiceImages: [],
            destination: '',
            departure: '',
            content: '',
            imagePath: [],
            number: [],
            submitting: false,
            departureMinimumDate:new Date(),
            returnMinimumDate:new Date(),
            showDatePickerIOS:false,
            dateType:1,
        }
    }
   

    componentDidMount() {
    }

    async showTimePicker(type) {
         if (Platform.OS === 'android') {
            try {
                const {action, year, month, day} = await DatePickerAndroid.open({
                    date: new Date(),
                });
                if (action === DatePickerAndroid.dismissedAction) {
                    Toast.show('已取消选择');
                }
                if (action === DatePickerAndroid.dateSetAction) {
                    let date = this.state.date;
                    date[timeType] = year + '-' + (month + 1) + '-' + day;
                    this.setState({
                        date,
                    })
                }
            } catch ({code, message}) {
                Toast.show('操作失败')
            }
        } else {

        }

        if (Platform.OS === 'ios') {
            
            let isShow = this.state.showDatePickerIOS; 
             this.setState({  
                    showDatePickerIOS:!isShow,
                    dateType:type  
                });  
           
           
        }
    }


    onDateChange(date) {
        
        let departureDate = date.getFullYear() + '-' + (date.getMonth()+ 1) + '-' + date.getDate();
        console.log(departureDate);

       if (this.state.dateType === 1)
       {
                this.setState({
                            departureMinimumDate:date,
                            departureDate: departureDate,
                            returnMinimumDate:date,
                            returnDate: departureDate,
                        });
       }else
       {
                this.setState({
                             returnMinimumDate:date,
                            returnDate: departureDate,
                         });
       }
        
    }

    returnModalDatePickerView(){
        return (
             <Modal  
                                animationType='slide'  
                                transparent={true}  
                                visible={this.state.showDatePickerIOS}  
                                onShow={() => {}}  
                                onRequestClose={() => {}} > 
                             <View style={styles.modalStyle}>  
                                  <TouchableOpacity style={{}}
                                              onPress={() => this.showTimePicker(this.state.dateType)}>
                                              <View style={styles.DatePickerCancelView}> 
                                              </View> 
                                  </TouchableOpacity>
                                 <DatePickerIOS style={styles.DatePickerView}
                                    mode='date'
                                    date={this.state.dateType===1 ? this.state.departureMinimumDate:this.state.returnMinimumDate}
                                    minimumDate={this.state.dateType===1 ?new Date():this.state.departureMinimumDate}
                                    onDateChange={(data) => this.onDateChange(data)}
                                    />
                            </View> 
                           </Modal>
                          

        );
    }

    choiceImage() {
        if (this.state.imagePath.length == 8) {
            Toast.show("最多选择8张图片");
            return;
        }
        let options = {
            title: '请选择图片',
            cancelButtonTitle: '取消',
            chooseFromLibraryButtonTitle: '从手机相册选择',
            takePhotoButtonTitle: '从相机拍照获取',
            allowsEditing: true,
            maxWidth: 750,
            maxHeight: 1280,
            quality:0.75,
        };
        ImagePicker.showImagePicker(options, (res) => {
            if (res.didCancel) {
                Toast.show('已取消选择');
            } else if (res.error) {
                Toast.show('选择图片错误');
            } else if (res.customButton) {

            } else {
                let source = '';
                let path = '';
                if (Platform.OS === 'ios') {
                    path = res.uri.replace('file://', '');
                    source = {uri: res.uri.replace('file://', ''), isStatic: true};
                } else {
                    source = {uri: res.uri, isStatic: true};
                    path = res.path;
                }
                this.setState({
                    choiceImages: this.state.choiceImages.concat(source),
                    imagePath: this.state.imagePath.concat(path),
                });
            }
        });
    }

    initiatedWithTour() {
        Keyboard.dismiss();
        if (this.state.destination.length == 0) {
            Toast.show("请输入目的地");
            return;
        }
        if (this.state.departure.length == 0) {
            Toast.show("请输入出发地");
            return;
        }
        if (this.state.content.length == 0) {
            Toast.show("请输入内容");
            return;
        }
        if (Number(DateUtil.timestamp(this.state.departureDate)) > Number(DateUtil.timestamp(this.state.returnDate))) {
            Toast.show("请选择正确的日期");
            return;
        }
        console.log(this.state.destination);
        console.log(this.state.departure);
        console.log(this.state.content);
        console.log(this.state.departureDate);
        console.log(this.state.returnDate);
        this.setState({
            submitting: true,
        });
        FoundAPIService.initiatedWithTour(Global.Const.token, Global.Const.registeredId,
            this.state.departureDate, this.state.returnDate, this.state.destination, this.state.departure, this.state.content).then((ret)=> {
            if (this.state.imagePath.length > 0) {
                for (var i = 0; i < this.state.imagePath.length; i++) {
                    FoundAPIService.updateImg(Global.Const.token, Global.Const.registeredId, ret, this.state.imagePath[i]).then((ret)=> {
                        this.setState({
                            number: this.state.number.concat(i),
                        });
                        if (this.state.number.length == this.state.imagePath.length) {
                            this.setState({
                                submitting: false,
                            });
                            Toast.show("发布成功");
                            console.log('上传图片了');
                            this.props.navigator.pop();
                        }
                    }).catch((err)=> {
                        this.setState({
                            submitting: false,
                        });
                    });
                }
            } else {
                this.setState({
                    submitting: false,
                });
                Toast.show("发布成功");
                console.log('没有上传图片');
                this.props.navigator.pop();
            }

        }).catch((err)=> {
            this.setState({
                submitting: false,
            });
        });

    }

    render() {
        return (
            <TouchableOpacity activeOpacity={1} style={{flex: 1}} onPress={() => {
                Keyboard.dismiss();
            }}>
                <View style={{flex: 1, backgroundColor: '#F2F3F5'}}>
                    <ToolBar
                        leftFunc={()=> this.props.navigator.pop()}
                        title="发起自驾同游"
                        rightFunc={()=> {
                           this.initiatedWithTour();
                        }}
                        rightImage={require('../../Image/release_icon.png')}
                    />
                    <ScrollView>
                           { Platform.OS === 'ios' ? this.returnModalDatePickerView():null}
                            <View style={styles.datePickerBox}>
                            <TouchableOpacity style={{flex: 1,height: 50,  }}
                                              onPress={() => this.showTimePicker(1)}
                            >
                                <View
                                    style={{flex: 1,justifyContent: 'space-around',borderRightColor: '#ccc',borderRightWidth: 1}}>
                                    <Text style={{fontSize: 12,color: Global.FontColor.LightGrey}}>出发日</Text>
                                    <Text
                                        style={{fontSize: 16,color: Global.FontColor.DarkGray}}>{this.state.departureDate}</Text>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity style={{flex: 1}}
                                              onPress={() => this.showTimePicker(2)}
                            >
                                <View style={{ flex: 1, justifyContent: 'space-around', paddingLeft: 10,  }}>
                                    <Text style={{ fontSize: 12, color: Global.FontColor.LightGrey }}>返回日</Text>
                                    <Text
                                        style={{ fontSize: 16, color: Global.FontColor.DarkGray }}>{this.state.returnDate}</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={styles.flexRow}>
                            <Text style={{
                            fontSize: 12,
                            color: Global.FontColor.LightGrey
                        }}>目的地</Text>
                            <TextInput
                                placeholder={'请输入目的地'}
                                underlineColorAndroid={'rgba(0,0,0,0)'}
                                style={styles.contentText}
                                returnKeyType={'done'}
                                maxLength={20}
                                value={this.state.destination}
                                onChangeText={destination => this.setState({ destination })}

                            />
                        </View>
                        <View style={styles.flexRow}>
                            <Text style={{
                            fontSize: 12,
                            color: Global.FontColor.LightGrey
                        }}>出发地</Text>
                            <TextInput
                                placeholder={'请输入出发地'}
                                underlineColorAndroid={'rgba(0,0,0,0)'}
                                style={styles.contentText}
                                returnKeyType={'done'}
                                maxLength={20}
                                value={this.state.departure}
                                onChangeText={departure => this.setState({ departure })}
                            />
                        </View>
                        <Text style={{
                        padding: 15,
                        backgroundColor: 'white',
                        marginBottom: 1,
                        fontSize: 12,
                        color: Global.FontColor.LightGrey
                    }}>说明</Text>
                        <TextInput
                            style={{
                            height: 150,
                            backgroundColor: 'white',
                            padding: 15,
                            marginBottom: 1,
                            fontSize: 14,
                            lineHeight: 25,
                        }}
                            placeholder={'请输入内容'}
                            multiline={true}
                            maxLength={300}
                            underlineColorAndroid={'rgba(0,0,0,0)'}
                            textAlignVertical={'top'}
                            value={this.state.content}
                            onChangeText={content => this.setState({ content })}
                        />
                        <View style={styles.choiceImagesBox}>
                            {
                                this.state.choiceImages ?
                                    this.state.choiceImages.map((item, index) => {
                                        return (
                                            <Image
                                                key={'image' + index}
                                                style={styles.image}
                                                source={item}
                                            />
                                        )
                                    }) : null
                            }
                            <TouchableOpacity
                                onPress={() => this.choiceImage()}
                            >
                                <Image style={styles.image} source={require('../../Image/photo_input.png')}/>
                            </TouchableOpacity>
                        </View>
                    </ScrollView>
                </View>
                {this.state.submitting ? <View
                    style={{position: 'absolute',top:0,left:0,width:Global.Const.size.width,height:Global.Const.size.height,backgroundColor:null,alignItems:'center',justifyContent:'center'}}>
                    <View
                        style={{backgroundColor:'#333333',borderRadius:5, alignItems: 'center',justifyContent: 'center',width:80,height:80}}>
                        <ActivityIndicator
                            animating={this.state.animating}
                            style={{ alignItems: 'center',justifyContent: 'center'}}
                            size="large"/>
                        <Text style={{color:'white'}}>正在提交</Text>
                    </View>
                </View> : null}
            </TouchableOpacity>

        )
    }
}

{/*<View style={{*/
}
{/*flexDirection: 'row',*/
}
{/*alignItems: 'center',*/
}
{/*padding: 10,*/
}
{/*backgroundColor: 'white',*/
}
{/*}}>*/
}
{/*<Text style={{*/
}
{/*fontSize: 14,*/
}
{/*marginRight: 5*/
}
{/*}}>分享到</Text>*/
}
{/*<Image style={{*/
}
{/*width: 30,*/
}
{/*height: 30,*/
}
{/*marginRight: 5*/
}
{/*}} source={require('../../Image/ic_modify_weixin.png')}/>*/
}
{/*<Image style={{*/
}
{/*width: 30,*/
}
{/*height: 30,*/
}
{/*marginRight: 5*/
}
{/*}} source={require('../../Image/ic_modify_qq.png')}/>*/
}
{/*</View>*/
}

export default InitiatedWithTour;